import socket
import threading
import time

def send_message(thread_id):
    """Sends a message and receives the response."""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect(("127.0.0.1", 8000))
            message = f"Thread-{thread_id}"
            s.sendall(message.encode())
            print(f"Thread {thread_id}: Sent '{message}'")

            # Receive data (adjust buffer size if needed)
            data = s.recv(1024)
            if data:
                print(f"Thread {thread_id}: Received: '{data.decode()}'")
            else:
                print(f"Thread {thread_id}: No data received.")

    except ConnectionRefusedError:
        print(f"Thread {thread_id}: Connection refused. Is the server running?")
    except ConnectionResetError:
        print(f"Thread {thread_id}: Connection reset by peer.")
    except Exception as e:
        print(f"Thread {thread_id}: Error: {e}")

def main():
    num_threads = 20
    threads = []

    for i in range(num_threads):
        thread = threading.Thread(target=send_message, args=(i + 1,))
        threads.append(thread)
        thread.start()
        # time.sleep(0.05)  # Small delay to avoid overwhelming the server

    for thread in threads:
        thread.join()

    print("All threads finished.")

if __name__ == "__main__":
    main()